package com.example.mybatisplus.web.controller;

import ch.qos.logback.core.LayoutBase;
import com.example.mybatisplus.model.domain.Movie;
import com.example.mybatisplus.model.domain.User;
import com.example.mybatisplus.service.MovieService;
import org.apache.tomcat.util.net.openssl.ciphers.Authentication;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.example.mybatisplus.common.JsonResponse;
import com.example.mybatisplus.service.FilmCollectionService;
import com.example.mybatisplus.model.domain.FilmCollection;

import java.util.List;
import java.util.stream.Collectors;


/**
 *
 *  前端控制器
 *
 *
 * @author fmx
 * @since 2024-11-17
 * @version v1.0
 */
@RestController
@RequestMapping("/api/filmCollection")
public class FilmCollectionController {

    private final Logger logger = LoggerFactory.getLogger( FilmCollectionController.class );

    @Autowired
    private FilmCollectionService filmCollectionService;
    //???
    @Autowired
    private MovieService movieService;

    /**
    * 描述：根据Id 查询
    *
    */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getById(@PathVariable("id") Long id)throws Exception {
        FilmCollection  filmCollection =  filmCollectionService.getById(id);
        return JsonResponse.success(filmCollection);
    }

    /**
    * 描述：根据Id删除
    *
    */
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    @ResponseBody
    public JsonResponse deleteById(@PathVariable("id") Long id) throws Exception {
        filmCollectionService.removeById(id);
        return JsonResponse.success(null);
    }


    /**
    * 描述：根据Id 更新
    *
    */
    @RequestMapping(value = "", method = RequestMethod.PUT)
    @ResponseBody
    public JsonResponse updateFilmCollection(FilmCollection  filmCollection) throws Exception {
        filmCollectionService.updateById(filmCollection);
        return JsonResponse.success(null);
    }


    /**
    * 描述:创建FilmCollection
    *
    */
    @RequestMapping(value = "", method = RequestMethod.POST)
    @ResponseBody
    public JsonResponse create(FilmCollection  filmCollection) throws Exception {
        filmCollectionService.save(filmCollection);
        return JsonResponse.success(null);
    }

    //收藏电影
    /**
     * 描述:添加FilmCollection
     *
     */
    @PostMapping("collections")
    public void addFilmCollection(@RequestBody FilmCollection filmCollection) {
        // 调用服务层方法添加收藏记录
        filmCollectionService.addFilmCollection(filmCollection.getUserId(),filmCollection.getMovieId());

        // 可以返回响应信息
    }

    //删除收藏
    /**
     * 描述:删除FilmCollection
     *
     */
    @DeleteMapping("/collections/{userId}/{movieId}")
    public void deleteFilmCollection(@PathVariable Integer userId, @PathVariable Integer movieId) {
        // 调用服务层方法删除收藏记录
        filmCollectionService.deleteFilmCollection(userId, movieId);

        // 可以返回响应信息
    }

    // 根据user_id查询收藏的movie信息
    /**
     * 描述:根据用户ID查询用户的FilmCollection
     *
     */
    @GetMapping("/collections/{userId}/movies")
    public List<Movie> getUserCollectedMovies(@PathVariable Integer userId) {
        // 调用服务层方法获取收藏的movie_id列表

        List<Integer> movieIds = filmCollectionService.getCollectedMovieIdsByUserId(userId);

        // 调用服务层方法根据movie_id列表获取详细的movie信息
        List<Movie> movies = movieService.getMoviesByIds(movieIds);

        // 返回详细的movie信息列表
        return movies;
    }

    /**
     * 描述:查询FilmCollection是否已存在，并返回布尔值
     *
     */
    @GetMapping("/check/{userId}/{movieId}")
    public ResponseEntity<Boolean> checkIfUserHasMovie(@PathVariable Integer userId, @PathVariable Integer movieId) {
        boolean exists = filmCollectionService.checkIfUserHasMovie(userId, movieId);
        return ResponseEntity.ok(exists);
    }

    /**
     * 描述:能够根据用户提供的movie_id、电影名和电影类型搜索符合条件的电影
     *
     */
    @GetMapping("/collections/{userId}/movies/search")
    public ResponseEntity<List<Movie>> searchUserCollectedMovies(
            @PathVariable Integer userId,
            @RequestParam(required = false) Integer movieId,
            @RequestParam(required = false) String movieName,
            @RequestParam(required = false) String movieType) {

        // 根据userId获取用户收藏的电影ID列表
        List<Integer> collectedMovieIds = filmCollectionService.getCollectedMovieIdsByUserId(userId);

        // 如果提供了movieId，则只保留匹配的ID
        if (movieId != null) {
            collectedMovieIds = collectedMovieIds.stream()
                    .filter(id -> id.equals(movieId))
                    .collect(Collectors.toList());
        }

        // 如果提供了movieName或movieType，则调用服务层方法根据这些条件过滤电影
        List<Movie> filteredMovies = movieService.getMoviesByIds(collectedMovieIds);
        if (movieName != null || movieType != null) {
            filteredMovies = filteredMovies.stream()
                    .filter(movie -> (movieName == null || movie.getMovieName().contains(movieName)) &&
                            (movieType == null || movie.getMovieType().equals(movieType)))
                    .collect(Collectors.toList());
        }

        // 返回过滤后的电影列表
        return ResponseEntity.ok(filteredMovies);
    }

}

